package com.junzichangsheng.crawlerXFL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CrawlerXFL_Info {
    private String MAIN_PREFIX;
    private boolean IS_SKIP;
    private String WEBSITE_PREFIX;
    private String CARTOON_PATH;
    private Integer EPISODE_BEGIN_PAGE;
    private Integer EPISODE_END_PAGE;
    private int DEGREE;
    private int TIMEOUT_MILLIS = 20*1000;
    private int THREADPOOL_NUM = 5;
    private boolean IS_THREADPOOL = false;

    public CrawlerXFL_Info(String MAIN_PREFIX, boolean IS_SKIP, String WEBSITE_PREFIX, String CARTOON_PATH, Integer EPISODE_BEGIN_PAGE, Integer EPISODE_END_PAGE, int DEGREE) {
        this.MAIN_PREFIX = MAIN_PREFIX;
        this.IS_SKIP = IS_SKIP;
        this.WEBSITE_PREFIX = WEBSITE_PREFIX;
        this.CARTOON_PATH = CARTOON_PATH;
        this.EPISODE_BEGIN_PAGE = EPISODE_BEGIN_PAGE;
        this.EPISODE_END_PAGE = EPISODE_END_PAGE;
        this.DEGREE = DEGREE;
    }

    public void getCartoon() throws Exception {
        Document document = Jsoup.parse(new URL(CARTOON_PATH), TIMEOUT_MILLIS);
        System.out.println("elements");
        Element element = document.body().getElementsByClass("container").get(2)
                .getElementsByClass("box").get(0)
                .getElementsByClass("left").get(0);
        String title = element.getElementsByTag("h2").get(0).text();
        String coverImg = element.getElementsByClass("image").get(0).getElementsByTag("img").get(0).attr("data-original");

        if(IS_SKIP && new File(MAIN_PREFIX + regexName(title)).exists()){
            System.out.println("=====漫画《" + title + "》已存在===================");
        }else {
            //获取线程池
            ExecutorService executorService = Executors.newFixedThreadPool(THREADPOOL_NUM);
            //下载
            System.out.println("=====下载《" + title + "》中..=======================================================================================");
            getEpisodeList(title,CARTOON_PATH,executorService);
            //保存封面
            InputStream inputStream = new URL(coverImg).openStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            File file = new File(MAIN_PREFIX + regexName(title) + "/" + "封面.jpg");
            FileUtils.writeByteArrayToFile(file,bytes);
            System.out.println("=====下载《" + title + "》完成=======================================================================================\n");
            //关闭线程池
            executorService.shutdown();
        }
    }

    private void getEpisodeList(String cartoonName,String cartoonPath,ExecutorService executorService) throws Exception {
        Document document = Jsoup.parse(new URL(cartoonPath), TIMEOUT_MILLIS);
        Elements elements = document.body().getElementsByClass("list_box").get(1).getElementsByClass("t1");
        //获取起止话数
        int beginPage = EPISODE_BEGIN_PAGE != null ? EPISODE_BEGIN_PAGE : 1;
        int endPage = EPISODE_END_PAGE != null ? EPISODE_END_PAGE : elements.size();
        for(int i = beginPage;i <= endPage;i++){
            Element element = elements.get(i - 1).getElementsByTag("a").get(0);
            String path = element.attr("href");
            String title = element.getElementsByClass("title").get(0).text();
            System.out.print("下载《" + title + "》中...    ");
            getCartoonDetail(cartoonName,title,path,executorService);
            System.out.println("下载《" + title + "》完成！");
        }
    }

    private void getCartoonDetail(String cartoonName,String episodeName,String episodePath,ExecutorService executorService) throws Exception {
        Document document = Jsoup.parse(new URL(WEBSITE_PREFIX + episodePath), TIMEOUT_MILLIS);
        Elements elements = document.body().getElementsByClass("image").get(0).getElementsByTag("img");
        //遍历文件路径信息
        for(int i = 1;i <= elements.size();i++){
            Element element = elements.get(i - 1);
            String path = element.attr("data-original");
            String zeroPrefix = String.format("%03d",i);
            String filePath = MAIN_PREFIX + regexName(cartoonName) + "/" + regexName(episodeName) + "/" + zeroPrefix + ".jpg";
            if(IS_THREADPOOL){
                executorService.execute(() -> {
                    try {
                        InputStream inputStream = new URL(path).openStream();
                        BufferedImage sourceImg = ImageIO.read(inputStream);
                        File file = new File(filePath);
                        if(!file.exists()) {
                            file.getParentFile().mkdirs();
                            file.createNewFile();
                        }
                        ImageIO.write(sourceImg, "jpg", file);
                    } catch (IOException e) {
                        //关闭线程池
                        executorService.shutdown();
                        //报错
                        e.printStackTrace();
                    }
                });
            }else {
                InputStream inputStream = new URL(path).openStream();
                BufferedImage sourceImg = ImageIO.read(inputStream);
                File file = new File(filePath);
                if(!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                ImageIO.write(sourceImg, "jpg", file);
            }
        }
    }

    private String regexName(String name){
        String regex = "[\\\\/:*?\"<>|]";
        return name.replaceAll(regex,"");
    }
}
